package com.itcast.ui;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import weibo4android.Trend;
import weibo4android.Trends;
import weibo4android.User;
import weibo4android.WeiboException;

import com.itcast.logic.MainService;
import com.itcast.logic.Task;
import com.itcast.ui.R;
import com.itcast.ui.CommentActivity.MyAdapter;
import com.itcast.util.GPSPoint;
import com.itcast.util.TextViewLink;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class NewWeiboActivity extends Activity implements TextWatcher {
	private EditText et;
	private TextView tvLabel,trend, mention, emotion;
	public boolean hasPic = false;
	public boolean hasGPS = false;
	public byte dat[];// 图片数据
	public double gps[];// 经纬度数据
	private ImageView ivPic;
	private boolean useCamera = false;
	private AlertDialog ad;
	private Bitmap myBitmap;
	private GridView myGridView ;
	private ListView myListView;
	private ArrayList<HashMap<String, String>> myList;
	private SimpleAdapter mSchedule ;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.newblog);
		
		
		myGridView = (GridView)findViewById(R.id.myGridView);
		 myListView = (ListView) findViewById(R.id.myListView);
		// 得到输入文字的文本框
		et = (EditText) this.findViewById(R.id.etBlog);
		et.addTextChangedListener(this);
		et.setHeight(300);
		// 得到剩余字数
		tvLabel = (TextView) this.findViewById(R.id.tvLabel);
		
		 final AlertDialog.Builder labelBuilder = new AlertDialog.Builder(this);
		tvLabel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(et.getText().length() == 0)	return ;
				labelBuilder.setMessage("要删除所有文字吗？").setPositiveButton("是", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						et.setText("");
					}
				}).setNegativeButton("否", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						
					}
				});
				AlertDialog ad = labelBuilder.create();
				ad.show();
			}
			
		});
		
		// 得到顶部的按钮设定返回和发表
		View titleview = this.findViewById(R.id.title);
		// 返回
		Button btNewbolg = (Button) titleview.findViewById(R.id.title_bt_left);
		btNewbolg.setBackgroundResource(R.drawable.title_back);
		btNewbolg.setText("返回");
		btNewbolg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (myGridView.getVisibility() == View.VISIBLE) {
					myGridView.setVisibility(View.GONE);
				} else if (myListView.getVisibility() == View.VISIBLE) {
					myListView.setVisibility(View.GONE);
				} else if (et.getText().toString().length() != 0) {
					dialog();
				} else
					finish();
			
			}

		});
		// 发表
		Button btRefbolg = (Button) titleview.findViewById(R.id.title_bt_right);
		btRefbolg.setText("发表");
		btRefbolg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				HashMap hm = new HashMap();
				hm.put("msg", et.getText().toString());
				if (hasGPS) {
					hm.put("gpspoint", gps);
					Task ts = new Task(Task.TASK_NEW_WEIBO_GPS, hm);
					MainService.addNewTask(ts);
				} else if (hasPic) {
					hm.put("picdat", dat);
					Task ts = new Task(Task.TASK_NEW_WEIBO_PIC, hm);
					MainService.addNewTask(ts);
				} else {
					Task ts = new Task(Task.TASK_NEW_WEIBO, hm);
					MainService.addNewTask(ts);
				}
				finish();
			}
		});

		final String[] items = { "照相机", "图库" };
		final String[] itemsMore = { "照相机", "图库", "删除图片" };

		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// 添加图片按钮
		TextView btaddPic = (TextView) this.findViewById(R.id.btGallery);
		btaddPic.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				DialogInterface.OnClickListener myListener = new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						// myTV.setText(items[which]);
						ad.dismiss();
						if (which == 0) {
							useCamera = true;
							Intent i = new Intent(
									"android.media.action.IMAGE_CAPTURE");
							startActivityForResult(i,
									0);

						} else if (which == 1) {
							useCamera = false;
							Intent intent = new Intent();
							intent.setType("image/*");
							intent.setAction(Intent.ACTION_GET_CONTENT);
							startActivityForResult(intent, 1);
						} else if (which == 2) {
							ivPic.setBackgroundResource(0);
							ivPic.setVisibility(View.INVISIBLE);
							hasPic = false;
						}
					}
				};

				if (!hasPic)
					builder.setTitle("请选择图片上传方式").setSingleChoiceItems(items,
							-1, myListener);
				else
					builder.setTitle("请选择图片上传方式").setSingleChoiceItems(
							itemsMore, -1, myListener);
				ad = builder.create();
				ad.show();
			}
		});
		// 添加经纬度
		TextView btaddGPS = (TextView) this.findViewById(R.id.btGPS);
		btaddGPS.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				gps = GPSPoint.getGPSPoint(NewWeiboActivity.this);
				if (gps != null) {
					Toast.makeText(getApplicationContext(),
							"您已成功添加地理位置信息 " + gps[0] + " " + gps[1],
							Toast.LENGTH_LONG).show();
					hasGPS = true;
					MainService.nowUser.setGeoEnabled(true);
				} else
					Toast.makeText(getApplicationContext(), "无法添加地理位置信息 ",
							Toast.LENGTH_LONG).show();

			}
		}); 
	
	
		//下面是实现@、话题、表情的3个功能的事件监听
		trend = (TextView) findViewById(R.id.trend);
		mention = (TextView) findViewById(R.id.mention);
		emotion = (TextView) findViewById(R.id.emotion);
		
		trend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				et.setHeight(50);
				Toast.makeText(getApplicationContext(),
						"1: "+et.getHeight(),
						Toast.LENGTH_LONG).show();
				toTrend();
			}
		});
		
		mention.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				et.setHeight(50);
				toMention();
				
			}
		});
		
		emotion.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				et.setHeight(250);
				toEmotion();
				
			}
		});
		
	}

	protected void toEmotion() {
		//下边2句注释掉代码表示进行下载获取
//		Task ts = new Task(Task.TASK_GET_EXPRESSION_IMAGE_ICON, null);
//		MainService.addNewTask(ts);
		
		//(因为点击话题按钮再点击表情，话题的listview会挡住表情列表，所以要把它隐藏)
		
		if(myListView.getVisibility() == View.VISIBLE)
		myListView.setVisibility(View.GONE);

		
		 
		 myGridView.setVisibility(View.VISIBLE);
		myGridView.setNumColumns(6);
		//初始化adapter和CommentActivity的handler
		CommentActivity.myAdapter = new MyAdapter(this);
		myGridView.setAdapter(CommentActivity.myAdapter);
		if(CommentActivity.handler == null)
		CommentActivity.handler = new Handler(){
			@Override
			//当有消息发送出来的时候就执行Handler的这个方法
			public void handleMessage(Message msg){
			super.handleMessage(msg);
			CommentActivity.myAdapter.notifyDataSetChanged();
			}
			};
		
		 OnItemClickListener itemListener = new OnItemClickListener() { 
	         public void onItemClick(AdapterView<?> parent, View view, 
	        		 int position, long id) { 
	            
	             final String message = "OnTouchGrid:Icon No."  + id+" is Touched."; 
	              Toast.makeText(getApplicationContext(), message, 1000).show(); 
	         
	              et.setHeight(300);
	              
	           // 得到drawable对象，即所有插入的图片
					Drawable d = getResources().getDrawable(CommentActivity.myAdapter.imgs[position]);
					d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
					// 用这个drawable对象代替字符串
					ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
					String picName = getResources().getResourceName(CommentActivity.myAdapter.imgs[position]).split("/")[1];
					String phrase ="["+ TextViewLink.getPicDescription(picName, getApplicationContext()) +"]";
					SpannableString ss = new SpannableString(phrase);
					// 包括0但是不包括phrase.length()
					ss.setSpan(span, 0, ss.length(),
							Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
					et.append(ss);
					
					 myGridView.setVisibility(View.GONE);
					 Log.d("QQQ", "OnItemClickListener"); 
	         }  
	     }; 
	     myGridView.setOnItemClickListener(itemListener);
	}
  
	protected void toMention() {
		// TODO Auto-generated method stub
		Toast.makeText(getApplicationContext(), "mention", Toast.LENGTH_LONG).show();
		//editText.setHeight(20);
		
		
		 //绑定XML中的ListView，作为Item的容器
        myListView = (ListView) findViewById(R.id.myListView);  
        myListView.setVisibility(View.VISIBLE);
		//生成动态数组 
        myList = new ArrayList<HashMap<String, String>>();  
        List<User> userList = null;
		try {
			userList = MainService.mainService.weibo.getFriendsStatuses();
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("friendName",	"@");
		 myList.add(map);
		for (int i = 0; i < userList.size(); i++) {
			User friend = userList.get(i);
			String name = friend.getName();
			map = new HashMap<String, String>();
			 map.put("friendName",	name);
			 myList.add(map);
			Toast.makeText(getApplicationContext(), name,Toast.LENGTH_SHORT).show();
			}
		
        
        //生成适配器，数组===》ListItem  
         mSchedule = new SimpleAdapter(this, //没什么解释
               myList,//数据来源   
               R.layout.friend_item,//ListItem的XML实现  
           //动态数组与ListItem对应的子项    
          new String[] {"friendName"},   
                                                      
             //ListItem的XML文件里面的TextView ID  
            new int[] {R.id.friend});  
         
         myListView.setAdapter(mSchedule); 
         myListView.setOnItemClickListener(new OnItemClickListener() {

             @Override
             public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) { 
                 // TODO Auto-generated method stub 
            	 et.setHeight(300);
              String friendName=(String) myList.get(arg2).get("friendName");
            
                 Toast.makeText(getApplicationContext(), "你点击了"+arg2+"项的"+friendName,Toast.LENGTH_SHORT).show();
                if(friendName == "@")
                	et.append("@");
                else
                	et.append("@"+friendName+" ");
                
                 	myListView.setVisibility(View.GONE);
             }
             });
		
	}

	protected void toTrend() {
		// TODO Auto-generated method stub
		
		//绑定XML中的ListView，作为Item的容器
        myListView = (ListView) findViewById(R.id.myListView);  
        myListView.setVisibility(View.VISIBLE);
		
		 List<Trends> trendList = null;
			try {
				trendList = MainService.mainService.weibo.getTrendsWeekly(0);
			} catch (WeiboException e) {
				// TODO Auto-generated catch block
				e.printStackTrace(); 
			}
			HashMap<String, String> map = new HashMap<String, String>();
			//生成动态数组 
	        myList = new ArrayList<HashMap<String, String>>();  
			map.put("friendName",	"##");
			 myList.add(map);
			for(int i = 0; i<trendList.size(); i++){ //事实上，这里的trendList.size()�?
				Trends trend =	trendList.get(i);
				Trend[] news = trend.getTrends();
				for(int j = 0; j<news.length; j++){
				String trendName =	news[j].getName();
				map = new HashMap<String, String>();
				 map.put("friendName",	trendName);
				 myList.add(map);
				//Toast.makeText(getApplicationContext(), trendName, Toast.LENGTH_LONG).show();
				}
			}
			//生成适配器，数组===》ListItem  
	         mSchedule = new SimpleAdapter(this, //没什么解释
	               myList,//数据来源   
	               R.layout.friend_item,//ListItem的XML实现  
	           //动态数组与ListItem对应的子项        
	          new String[] {"friendName"},   
	                                                      
	             //ListItem的XML文件里面的TextView ID  
	            new int[] {R.id.friend});  
	         
	         myListView.setAdapter(mSchedule); 
	         myListView.setOnItemClickListener(new OnItemClickListener() {
 
	             @Override
	             public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) { 
	                 // TODO Auto-generated method stub 
	            	 et.setHeight(300);
	              String friendName=(String) myList.get(arg2).get("friendName");
	            
	                 Toast.makeText(getApplicationContext(), "你点击了"+arg2+"项的"+friendName,Toast.LENGTH_SHORT).show();
	                if(friendName == "##"){
	                	et.append("##");
	                	et.requestFocus();
	                	et.setSelection(et.length()-1);
	                }
	                else
	                	et.append("#"+friendName+"# ");
	                
	                 	myListView.setVisibility(View.GONE);
	             }
	             });
	}
	
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		int i = 140 - arg0.length();
		tvLabel.setText(i+"");
	}
	
	public void afterTextChanged(Editable arg0) {
	}

	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) { 
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (myGridView.getVisibility() == View.VISIBLE) {
				myGridView.setVisibility(View.GONE);
				Toast.makeText(getApplicationContext(),
						myGridView.getVisibility() + "", 3000).show();
				return false;
			} else if (myListView.getVisibility() == View.VISIBLE) {
				myListView.setVisibility(View.GONE);
				Toast.makeText(getApplicationContext(),
						myGridView.getVisibility() + "", 3000).show();
				return false;
			} else if (et.getText().toString().length() != 0 || hasPic) {
				dialog();
				return false;
			} else
				return super.onKeyDown(keyCode, event);
		}
		return super.onKeyDown(keyCode, event);
	}

	//在退出前进行询问
	protected void dialog() {
		AlertDialog.Builder builder = new Builder(NewWeiboActivity.this);
		builder.setMessage("确定要退出编辑吗?");
		builder.setTitle("提示");
		builder.setPositiveButton("确认",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						arg0.dismiss();
						NewWeiboActivity.this.finish();
					}
				});
		builder.setNegativeButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		ivPic = (ImageView) findViewById(R.id.ivPic);
		//根据requestCode来判断不同的activity
		if (requestCode == 0) {
			if (resultCode == RESULT_OK) {
			Bundle extras = data.getExtras();
			 myBitmap = (Bitmap) extras.get("data");
 
			ivPic.setImageBitmap(myBitmap);
			hasPic = true;
			ivPic.setVisibility(View.VISIBLE);

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
			dat = baos.toByteArray();
			}
		} else if(requestCode == 1){
			if (resultCode == RESULT_OK) {
				Uri uri = data.getData();
				ContentResolver resolver = getContentResolver();
				Cursor cursor = resolver.query(uri, null, null, null, null);

				while (cursor.moveToNext()) {
					Log.i("====_id", cursor.getString(0) + "");
					Log.i("====_path", cursor.getString(1) + "");
					Log.i("====_size", cursor.getString(2) + "");
					Log.i("====_display_name", cursor.getString(3) + "");
				}
				try {
					BitmapFactory.Options options = new BitmapFactory.Options();
					// options.inSampleSize = 2;//图片宽高都为原来的二分之一，即图片为原来的四分之一
					// Bitmap
					// bitmap=BitmapFactory.decodeFile(cursor.getString(1),
					// options);
					InputStream in = resolver.openInputStream(uri);
					double size = in.available();
					Log.i("size", size + "");
					//图片在大于35K后要压缩(8.26M测试成功)
					 options.inSampleSize =(int) Math.ceil( Math.sqrt(size / 35000) );
					myBitmap = BitmapFactory.decodeStream(in, null, options);
					in.close();
					
					ivPic.setBackgroundResource(0);
					ivPic.setImageBitmap(myBitmap);
					hasPic = true;
					ivPic.setVisibility(View.VISIBLE);

					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
					dat = baos.toByteArray();

				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		else if(requestCode == 2){
			  if(resultCode==Activity.RESULT_OK){
				  ivPic.setBackgroundResource(0);
				  ivPic.setVisibility(View.INVISIBLE);
				  hasPic = false;
			  }
			 
		}
		
		if(hasPic){
		ivPic.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(NewWeiboActivity.this, ScrollImageActivity.class);
				intent.putExtra("image", dat);
				Log.i("FFF", dat.length+"");
				startActivityForResult(intent,2);
			}
		});
		}
		
	}
	
	protected void onDestroy(Bundle savedInstanceState) {
		if(! myBitmap.isRecycled()){
			myBitmap.recycle();
			System.gc();
		}
	}
	
	
}
